package com.gvfish.service;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.appengine.api.datastore.Key;
import com.gvfish.dao.AuthorityDao;
import com.gvfish.dao.RoleDao;
import com.gvfish.dao.UserDao;
import com.gvfish.entity.Authority;
import com.gvfish.entity.Role;
import com.gvfish.entity.User;

//@Service
public class SecurityManager {
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleDao roleDao;
	
	@Autowired
	private AuthorityDao authorityDao;
	
	public User findUserByLoginName(String name){
		return userDao.findByName(name);
	}
	public Set<Authority> getRoles(User user){
		Set<Authority> result = new HashSet<Authority>();
		if(user.getRoleKeys()==null)
			return result;
		for(Key key:user.getRoleKeys()){
			Role role = roleDao.getById(key.getId());
			if(role.getAuthorityKeys()==null)
				continue;
			for(Key authKey:role.getAuthorityKeys()){
				result.add(authorityDao.getById(authKey.getId()));
			}
		}
		return result;
	}
	public void changeRoleAuth(Long roleId,Long authorityId){
		roleDao.change(roleId, authorityId);
	}
	public void changeUserRole(Long roleId,String userName){
		userDao.changeUserRole(roleId, userName);
	}
}
